package com.test.algorithm;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.math.BigInteger;
import java.util.Collection;

//分表精确查找策略
public class MyPreciseTableShardingAlgorithm implements PreciseShardingAlgorithm<Long> {

    /**
     * select * from course where cid = ? or cid in (?,?)
     *
     * @param availableTargetNames 配置文件配置的真实表集合 [course_1，course_2]
     * @param shardingValue        配置表配置的逻辑表和主键 course以及主键存储的值
     * @return 真实表中的一个course_1或者course_2
     */
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Long> shardingValue) {
        //逻辑表名:course
        String logicTableName = shardingValue.getLogicTableName();
        //主键列名
        String columnName = shardingValue.getColumnName();
        //主键存储的值
        Long columnValue = shardingValue.getValue();

        //如下用代码实现 course_$->{cid%2+1)
        BigInteger columnValueBigInteger = BigInteger.valueOf(columnValue);
        BigInteger tableSuffix = (columnValueBigInteger.mod(new BigInteger("2"))).add(new BigInteger("1"));
        //真实表名
        String availableTargetName = logicTableName + "_" + tableSuffix;
        if (availableTargetNames.contains(availableTargetName)) {
            return availableTargetName;
        }
        throw new UnsupportedOperationException("route " + availableTargetName + " is not supported ,please check your config");
    }
}
